﻿using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Domain.PM;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;
using System.Transactions;

namespace FarmSmartSleep.Organ.API.Application.ProductionManagement.MotherWeaningFile
{
    /// <summary>
    /// 种母断奶
    /// </summary>
    public class MotherWeaningCreateHandler:IRequestHandler<MotherWeaningCreateCommon,Result>
    {
        private readonly IBaseRepository<MotherWeaning> motherWeaningRep;
        private readonly IBaseRepository<SleepInfor> sleepinforRep;
        /// <summary>
        /// 种母断奶构造函数
        /// </summary>
        /// <param name="motherWeaningRep"></param>
        /// <param name="_sleepinforRep"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public MotherWeaningCreateHandler(IBaseRepository<MotherWeaning> motherWeaningRep, IBaseRepository<SleepInfor> _sleepinforRep)
        {
            this.motherWeaningRep = motherWeaningRep;
            sleepinforRep = _sleepinforRep ?? throw new ArgumentNullException(nameof(_sleepinforRep));
        }
        /// <summary>
        /// 种母断奶 Handler方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(MotherWeaningCreateCommon request, CancellationToken cancellationToken)
        {
            var result = new Result { Code = (int)CodeEnum.add };

            // 尝试添加数据
            var n = await motherWeaningRep.AddRange(request.motherWeaning);
            try
            {
                using (TransactionScope tran = new(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
                {
                    // 检查添加结果
                    if (n > 0) // 假设 AddAsync 返回的 n 是影响的行数或插入的 ID
                    {
                        // 更新 SleepInfor 表的栋舍栏位
                        request.motherWeaning.ForEach(x =>
                        {
                            var list = sleepinforRep.GetAll().FirstOrDefault(c => c.SleepInforId == x.SowId);
                            list.RecordcottageId = x.TransferBarn;
                            list.FieIdId = x.TransferPen;
                            list.BreedStatuId = 1;//断奶后进入下一个阶段无状态
                            sleepinforRep.Update(list);
                        });

                        result.Code = (int)CodeEnum.success;
                        result.Messege = "添加成功";
                    }
                    else
                    {
                        result.Messege = "添加失败";
                    }
                    tran.Complete();
                    return result;
                }

            }
            catch (Exception)
            {
                result.Messege = "添加异常";
                throw;
            }
        }
    }
}
